<template>
  <el-dialog :title="mode === 'edit' ? '编辑网络信息' : '新增网络信息'" :visible.sync="visible" width="800px"
    :close-on-click-modal="false">
    <div class="dialog-body" style="max-height: 500px; overflow-y: auto; padding-right: 10px;">

      <el-form :model="localFormData" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ASN：" prop="asn">
              <el-input v-model="localFormData.asn" placeholder="请输入 ASN" clearable />
            </el-form-item>
            <el-form-item label="端口号：" prop="port">
              <el-input v-model="localFormData.port" placeholder="请输入端口号" clearable />
            </el-form-item>
            <el-form-item label="主机信息：" prop="host">
              <el-input v-model="localFormData.host" placeholder="请输入主机信息" clearable />
            </el-form-item>
            <el-form-item label="域名：" prop="domain">
              <el-input v-model="localFormData.domain" placeholder="请输入域名" clearable />
            </el-form-item>
            <el-form-item label="地区/行政区：" prop="region">
              <el-input v-model="localFormData.region" placeholder="请输入地区/行政区" clearable />
            </el-form-item>
            <el-form-item label="城市：" prop="city">
              <el-input v-model="localFormData.city" placeholder="请输入城市" clearable />
            </el-form-item>
            <el-form-item label="经度：" prop="longitude">
              <el-input v-model="localFormData.longitude" placeholder="请输入经度" clearable />
            </el-form-item>
            <el-form-item label="纬度：" prop="latitude">
              <el-input v-model="localFormData.latitude" placeholder="请输入纬度" clearable />
            </el-form-item>
            <el-form-item label="证书起始时间：" prop="cert.not_before">
              <el-date-picker v-model="localFormData.cert.not_before" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择起始时间" clearable />
            </el-form-item>
            <el-form-item label="证书到期时间：" prop="cert.not_after">
              <el-date-picker v-model="localFormData.cert.not_after" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择到期时间" clearable />
            </el-form-item>
            <el-form-item label="节点名称：" prop="node_name">
              <el-input v-model="localFormData.node_name" placeholder="请输入节点名称" clearable />
            </el-form-item>
            <el-form-item label="资源类型：" prop="resourceType">
              <el-input v-model="localFormData.resourceType" placeholder="请输入资源类型" clearable />
            </el-form-item>
            <el-form-item label="链接地址：" prop="link">
              <el-input v-model="localFormData.link" placeholder="请输入链接地址" clearable />
            </el-form-item>
            <el-form-item label="Header：" prop="header">
              <el-input type="textarea" v-model="localFormData.header" placeholder="请输入 Header" clearable />
            </el-form-item>
            <el-form-item label="Header Hash：" prop="header_hash">
              <el-input v-model="localFormData.header_hash" placeholder="请输入 Header Hash" clearable />
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
              <el-input type="textarea" v-model="localFormData.remark" placeholder="请输入备注" clearable />
            </el-form-item>
            <el-form-item label="Banner Hash：" prop="banner_hash">
              <el-input v-model="localFormData.banner_hash" placeholder="请输入 Banner Hash" clearable />
            </el-form-item>
            <el-form-item label="证书主体组织（Org）：" prop="cert.subject.org" class="custom-label">
              <el-input v-model="localFormData.cert.subject.org" placeholder="请输入证书主体 Org" clearable />
            </el-form-item>
            <el-form-item label="证书主体组织（CN）：" prop="cert.subject.cn" class="custom-label">
              <el-input v-model="localFormData.cert.subject.cn" placeholder="请输入证书主体 CN" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IP 地址：" prop="ip">
              <el-input v-model="localFormData.ip" placeholder="请输入 IP 地址" clearable />
            </el-form-item>
            <el-form-item label="协议类型：" prop="protocol">
              <el-input v-model="localFormData.protocol" placeholder="请输入协议类型" clearable />
            </el-form-item>
            <el-form-item label="基础协议：" prop="base_protocol">
              <el-input v-model="localFormData.base_protocol" placeholder="请输入基础协议" clearable />
            </el-form-item>
            <el-form-item label="标题信息：" prop="title">
              <el-input v-model="localFormData.title" placeholder="请输入标题" clearable />
            </el-form-item>

            <el-form-item label="国家代码：" prop="country">
              <el-input v-model="localFormData.country" placeholder="请输入国家代码" clearable />
            </el-form-item>
            <el-form-item label="国家名称：" prop="country_name">
              <el-input v-model="localFormData.country_name" placeholder="请输入国家名称" clearable />
            </el-form-item>
            <el-form-item label="证书域名：" prop="cert.domain">
              <el-input v-model="localFormData.cert.domain" placeholder="请输入证书域名" clearable />
            </el-form-item>
            <el-form-item label="证书序列号 SN：" prop="cert.sn">
              <el-input v-model="localFormData.cert.sn" placeholder="请输入证书序列号" clearable />
            </el-form-item>
            <el-form-item label="创建用户 SN：" prop="createUser">
              <el-input v-model="localFormData.createUser" placeholder="请输入创建用户" clearable />
            </el-form-item>

            <el-form-item label="TLS JA3S：" prop="tls.ja3s">
              <el-input v-model="localFormData.tls.ja3s" placeholder="请输入 JA3S 指纹" clearable />
            </el-form-item>
            <el-form-item label="TLS 版本：" prop="tls.version">
              <el-input v-model="localFormData.tls.version" placeholder="请输入 TLS 版本" />
            </el-form-item>
            <el-form-item label="备案号（ICP）：" prop="icp">
              <el-input v-model="localFormData.icp" placeholder="请输入备案号" clearable />
            </el-form-item>
            <el-form-item label="组织：" prop="org">
              <el-input v-model="localFormData.org" placeholder="请输入组织" clearable />
            </el-form-item>
            <el-form-item label="操作系统：" prop="os">
              <el-input v-model="localFormData.os" placeholder="请输入操作系统" clearable />
            </el-form-item>
            <el-form-item label="服务器：" prop="server">
              <el-input v-model="localFormData.server" placeholder="请输入服务器" clearable />
            </el-form-item>
            <el-form-item label="Banner：" prop="banner">
              <el-input type="textarea" v-model="localFormData.banner" placeholder="请输入 Banner 内容" clearable />
            </el-form-item>
            <el-form-item label="Banner FID：" prop="banner_fid">
              <el-input v-model="localFormData.banner_fid" placeholder="请输入 Banner FID" clearable />
            </el-form-item>
            <el-form-item label="证书发行机构（Org）：" prop="cert.issuer.org" class="custom-label">
              <el-input v-model="localFormData.cert.issuer.org" placeholder="请输入发行机构 Org" clearable />
            </el-form-item>
            <el-form-item label="证书发行机构（CN）：" prop="cert.issuer.cn" class="custom-label">
              <el-input v-model="localFormData.cert.issuer.cn" placeholder="请输入发行机构 CN" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <div style="text-align: right;">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
    mode: {
      type: String,
      default: 'add',
    },
  },
  data() {
    return {
      localFormData: this.getEmptyFormData(),
    }
  },
  watch: {
    visible(val) {
      if (val) {
        // 弹窗打开时，初始化表单
        if (this.mode === 'edit' && this.formData && Object.keys(this.formData).length > 0) {
          this.setFormData(this.formData);
        } else {
          this.resetForm();
        }
      } else {
        this.resetForm();
      }
    },
    formData: {
      handler(newVal) {
        if (this.visible && this.mode === 'edit' && newVal && Object.keys(newVal).length > 0) {
          this.setFormData(newVal);
        }
      },
      deep: true,
    },
  },
   methods: {
    getEmptyFormData() {
      return {
        asn: "",
        banner: "",
        banner_fid: "",
        banner_hash: "",
        base_protocol: "",
        cert: {
          domain: "",
          issuer: { cn: "", org: "" },
          not_after: "",
          not_before: "",
          sn: "",
          subject: { cn: "", org: "" }
        },
        city: "",
        country: "",
        country_name: "",
        createTime: "",
        createUser: "",
        domain: "",
        header: "",
        header_hash: "",
        host: "",
        icp: "",
        id: "",
        ip: "",
        jarm: "",
        latitude: "",
        link: "",
        longitude: "",
        node_name: "",
        org: "",
        os: "",
        port: "",
        protocol: "",
        region: "",
        remark: "",
        resourceType: "",
        server: "",
        title: "",
        tls: { ja3s: "", version: "" }
      };
    },
    unflattenObject(flatObj) {
      const result = {};
      for (const key in flatObj) {
        const value = flatObj[key];
        if (key.includes('.')) {
          const keys = key.split('.');
          let temp = result;
          for (let i = 0; i < keys.length; i++) {
            const part = keys[i];
            if (i === keys.length - 1) {
              temp[part] = value;
            } else {
              if (!temp[part]) temp[part] = {};
              temp = temp[part];
            }
          }
        } else {
          result[key] = value;
        }
      }
      return result;
    },
    deepMerge(target, source) {
      for (const key in source) {
        const val = source[key];
        if (val && typeof val === 'object' && !Array.isArray(val)) {
          if (!target[key] || typeof target[key] !== 'object') {
            this.$set(target, key, {});
          }
          this.deepMerge(target[key], val);
        } else {
          this.$set(target, key, val == null ? '' : val);
        }
      }
    },
    setFormData(data) {
      console.log('传入的 formData：', JSON.stringify(data, null, 2));
      const unflattened = this.unflattenObject(data);
      const base = this.getEmptyFormData();
      this.deepMerge(base, unflattened);
      this.localFormData = base;
    },
    resetForm() {
      this.localFormData = this.getEmptyFormData();
    },
    submitForm() {
      this.$emit('submit-complete', { ...this.localFormData });
    }
  }
}
</script>
<style>
.custom-label .el-form-item__label {
  font-size: 12px;
}
</style>